package com.prueba;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import com.archetypus.projectschedule.common.AlternateResource;
import com.archetypus.projectschedule.common.Configuration;
import com.archetypus.projectschedule.common.ServiceLocator;
import com.archetypus.projectschedule.web.common.cmd.ICommand;

public class Prueba implements ICommand {

	private static final long serialVersionUID = 1480986779246920648L;

	public void execute(HttpServletRequest request, HttpServletResponse response) {

		UserTransaction userTransaction = null;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String returnValue = new String();

		try {
			String jndiDS = Configuration.getInstance().get("jndiDS");

			DataSource dataSource = (DataSource) ServiceLocator.getInstance()
					.lookup(jndiDS);

			userTransaction = ServiceLocator.getInstance()
					.lookupUserTransaction();

			// begin
			userTransaction.begin();

			// consulta
			conn = dataSource.getConnection();
			stmt = conn.createStatement();

			/**
			 * String sql = " INSERT INTO activities( id, name, project )
			 * VALUES( 99, 'Pruebita', 1) "; stmt.executeUpdate(sql);
			 * 
			 * String cadena = " DELETE FROM activities ";
			 * stmt.executeUpdate(cadena);
			 */

			rs = stmt.executeQuery(" SELECT * FROM activities where id = "
					+ request.getParameter("val"));
			if (rs.next()) {

				returnValue += " BD: SFP - TABLA: activities - MDBS: MySQL ";
				returnValue += " \n Un registro de la BD ";
				returnValue += " \n Id: " + rs.getString("id");
				returnValue += " \n Name: " + rs.getString("name");
			} else {
				returnValue = " No se encontraron registros en Activities ";
			}
			// // commit
			userTransaction.commit();
			// userTransaction.rollback();

			request.setAttribute("consultaBD", returnValue);
			
			AlternateResource alternateResource = new AlternateResource();
			alternateResource.setActivateAltFlow(true);
			alternateResource.setAltFlowId("altFlow.1");
			request.setAttribute("alternateResource", alternateResource);

			
			/**
			 * request.getRequestDispatcher("/jsp/resultado.jsp").forward(request,
			 * response);
			 */

		} catch (Exception ex) {
			try {
				// rollback
				userTransaction.rollback();
			} catch (IllegalStateException e) {
			} catch (SecurityException e) {
			} catch (SystemException e) {
			}
			ex.printStackTrace();
		} finally {
			try {
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception e) {
			}
		}
	}
}